<template>
  <div class="trademak" v-loading="loading">
    <el-card>
      <div class="card_button">
        <div>
          <el-button type="primary" icon="Plus" @click="handleEdit_Add">添加品牌</el-button>
          <el-button type="danger" icon="Delete">批量删除</el-button>
        </div>
        <div>
          <el-button icon="Operation" circle plain />
          <el-button icon="Download" circle plain />
        </div>
      </div>
      <div class="card_table">
        <el-table :data="TrademarkList" style="width: 100%" max-height="670px">
          <el-table-column prop="" label="序号" width="100" align="center" type="index" />
          <el-table-column prop="tmName" label="品牌名称" align="center" />
          <el-table-column label="品牌LOGO" align="center">
            <template #default="{ row }">
              <el-image :src="row.logoUrl" lazy style="width: 100px; height: 100px" />
              <!-- <img :src="row.logoUrl"> -->
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleEdit_Add(scope.row)">
                修改
              </el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card_page">
        <Pagination :currentPage="currentPage" :total="total" :pageSize="pageSize" @CurrentChange="CurrentChange"
          @SizeChange="SizeChange"></Pagination>
      </div>
    </el-card>
    <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑品牌':'添加品牌'" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="Tname" label="品牌名名">
          <el-input v-model="formData.Tname" placeholder="请输入品牌名..." />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleCreateOrUpdate">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Trademark">
import { reactive, ref } from 'vue';
import { AddTrademarkAPI, DeleteTrademarkAPI, EditTrademarkAPI, TrademarkAPI } from '@/apis/product/trademark/index'
import type { UploadProps } from 'element-plus/es/components/upload/src/upload.mjs';
import type { FormInstance } from 'element-plus/es/components/form/index.mjs';
let currentPage = ref(1)
const total = ref(10)
const pageSize = ref(5)
const TrademarkList = ref([])
const loading = ref(true)
const dialogVisible = ref(false)

let activeID=ref()
// 表单
const formData = reactive({
  id:'',
  Tname: '',
  logoUrl: ''
})
const formRef = ref<FormInstance>()
// 表单规则
const formRules = reactive({
  Tname: [
    { required: true, message: '请输入品牌名...', trigger: 'blur' },
    { min: 1, max: 8, message: '长度为1-8位', trigger: 'blur' },
  ],
  logoUrl: [
    { required: true, message: '请上传LOGO' },
  ]
})


// 获取
const getTrademark = () => {
  TrademarkAPI(currentPage.value, pageSize.value).then((res) => {
    if (res.code == 200) {
      total.value = res.data.total
      TrademarkList.value = res.data.records
    }
  }).catch((err) => {
    TrademarkList.value = []
  }).finally(() => {
    loading.value = false
  })
}
// 当前页数改变
const CurrentChange = (value: number) => {
  currentPage.value = value
  getTrademark()
}
// 当前页面条数改变
const SizeChange = (value: number) => {
  pageSize.value = value
  getTrademark()
}
// 添加
// 修改
const handleEdit_Add = (row: any) => {
  if(row.id){
     formData.Tname=row.tmName
     formData.logoUrl=row.logoUrl
     formData.id=row.id
  }
  dialogVisible.value = true

}
// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`正在删除品牌：${row.tmName}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    DeleteTrademarkAPI(row.id).then((res) => {
      // console.log(res); //201接口
      ElMessage.success("删除成功")
      getTrademark()
    })
  })
}

// 文件上传前的验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const types = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']
  if (!types.includes(rawFile.type)) {
    ElMessage.error('文件格式错误...')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('文件大于4M...')
    return false
  }
  return true
}
// 文件上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // formData.logoUrl = URL.createObjectURL(uploadFile.raw!)
  formData.logoUrl = response.data
}

// 提交  接口可能不行了
const handleCreateOrUpdate = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      let api=formData.id ? EditTrademarkAPI:AddTrademarkAPI
      api(formData).then((res) => {
        // console.log(res);  //201接口
         ElMessage.success(formData.id ?'编辑成功...':'添加成功...')
        getTrademark()
      }).catch(() => {
        ElMessage.error(formData.id ?'编辑失败...':'添加失败，请重新添加...')
      }).finally(()=>{
        dialogVisible.value = false
      })
    } else {
      ElMessage.error('表单验证未通过...')
    }
  })
}

// 清除规则、
const resetForm = () => {
  if (!formRef.value) return
  dialogVisible.value = false
  formRef.value.resetFields()
}

// 获取品牌信息
getTrademark()
</script>

<style lang="scss" scoped>
.trademak {
  .card_button {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card_page {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
